package com.guaoran.source.rpc;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/13 16:27
 */
public class RpcTCPTransport {
    private String serviceAddress;

    public RpcTCPTransport(String serviceAddress) {
        this.serviceAddress = serviceAddress;
    }

    /**
     * 创建请求的连接
     * @return
     */
    private Socket newSocket(){
        Socket socket = null;
        try {
            String[] adds = serviceAddress.split(":");
            socket = new Socket(adds[0],Integer.parseInt(adds[1]));
            return socket;
        } catch (Exception e) {
           throw new RuntimeException("客户端创建连接失败"+e);
        }
    }

    /**
     * 发送请求信息到服务端
     * @param request
     * @return
     */
    public Object sendToServer(RpcRequest request){
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        Socket socket = null;
        try {
            //创建一个连接请求
            socket = newSocket();
            //将数据传输给服务端
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();
            //从输入流中获得服务端的响应
            inputStream = new ObjectInputStream(socket.getInputStream());
            Object object = inputStream.readObject();
            return object;
        } catch (Exception e) {
            throw new RuntimeException("发送请求到服务端失败"+e);
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
